package easy.二进制求和;

/**
 * 二进制求和
 *
 * @author CodeX
 * @since 2021-09-28 15:17:13
 */
public class AddBinary {
    public static String addBinary(String a, String b) {
        /*
         * 解题思路：列竖式形式计算和
         */
        int temp = 0, len = Math.max(a.length(), b.length());
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int i1 = i < a.length() ? Integer.parseInt(String.valueOf(a.charAt(a.length() - 1 - i))) : 0;
            int i2 = i < b.length() ? Integer.parseInt(String.valueOf(b.charAt(b.length() - 1 - i))) : 0;

            if (i1 + i2 + temp == 2) {
                ans.insert(0, "0");
                temp = 1;
            } else if (i1 + i2 + temp == 3) {
                ans.insert(0, "1");
                temp = 1;
            } else {
                ans.insert(0, (i1 + i2 + temp));
                temp = 0;
            }
        }

        if (temp == 1) {
            ans.insert(0, "1");
        }
        return ans.toString();
    }

    public static void main(String[] args) {
        String a = "1111", b = "111";
        System.out.println(addBinary(a, b));
    }
}
